package com.sea.physical.controller;


import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.operate.entity.RelatedSku;
import com.sea.physical.entity.TaxRate;
import com.sea.physical.service.TaxRateService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/physical/taxRate")
public class TaxRateController {

    @Autowired
    private TaxRateService taxRateService;

    @Autowired
    private DictDetailService dictDetailService;


    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        model.addAttribute("country",dictDetailService.findByTypeCode("base_country", null));
        return "/sea/physical/taxRate/main";
    }

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(Model model) {
        model.addAttribute("country",dictDetailService.findByTypeCode("base_country", null));
        return "/sea/physical/taxRate/add";
    }

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model,@RequestParam("id")Integer id) {
        model.addAttribute("country",dictDetailService.findByTypeCode("base_country", null));
        model.addAttribute("tax",taxRateService.findById(id));
        return "/sea/physical/taxRate/edit";
    }

    /**
     * 保存
     * @param taxRate
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(TaxRate taxRate) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != taxRate && taxRateService.save(taxRate) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前HSCODE已存在!");
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }
    /**
     * 保存
     * @param taxRate
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(TaxRate taxRate) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != taxRate && taxRateService.usave(taxRate) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前HSCODE已存在!");
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 保存
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxReturn delete(Integer id) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != id && taxRateService.delete(id) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前HSCODE已存在!");
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }


    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     TaxRate taxRate) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<TaxRate> list = taxRateService.findByCnd(taxRate);
        PageInfo<TaxRate> page = new PageInfo<TaxRate>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }


    /**
     * 导出收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, TaxRate taxRate) {
        List<TaxRate> list=taxRateService.findByCnd(taxRate);
        String[] title = {"国家","HS CODE","报关税率","清关税率"};
        String fileName = "税率信息" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "税率信息";
        String[][] content = new String[list.size()][4];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            TaxRate obj = list.get(i);
            content[i][0] = obj.getCountryName();
            content[i][1] = obj.getHSCode();
            content[i][2] = obj.getCustomsRate()+"%";
            content[i][3] = obj.getClearRate()+"%";
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
